Sistema de notificación push PHP y MySQL: Ejemplo Completo
Sistema de notificación push PHP y MySQL. En este artículo describiremos como incorporar un método para enviar mensajes personalizados y mostrarlo en los navegadores web como por ejemplo Chrome, Firefox, Opera, entre otros.
Sin embargo, las notificaciones push son útiles para informar a los usuarios con noticias específicas, correo electrónico nuevo, etc. Por lo tanto, si estás pensando en implementar un sistema de notificación web con PHP y MySQL, déjame decirte que estás en el lugar correcto.
Sistema de notificación push PHP y MySQL: Ejemplo Completo
Al terminar de analizar este artículo aprenderás a implementar el sistema de notificaciones push web con PHP y almacenarlo en la base de datos MySQL.
¿Cómo funciona el sistema de notificaciones Push?
Este sistema es muy intuitivo y funciona de la siguiente manera. El administrador puede crear notificaciones push web y esas notificaciones serán visibles a los usuarios que han iniciado sesión en su navegador. A continuación detallaremos algunos procesos que podemos realizar con el sistema.
- La notificación creada por el administrador puede mostrarse muchas veces según la configuración realizada.
- También podemos definir el tiempo de intervalo para la siguiente notificación que se emitirá.
- La notificación emitida se cerrará después de tiempo determinado por el administrador.
Estructura de archivos del sistema de notificaciones.
A continuación, mostraremos una imagen con la estructura del sistema mencionado.

CONTENIDO DEL SISTEMA DE NOTIFICACIONES PUSH
Siguiendo con la explicación, a continuación mostraremos los pasos y procesos del sistema.
Primer paso: Crear la base de datos y sus tablas.
Para que el sistema funcione tenemos que crear una tabla de notificaciones y esta tabla tendrá como nombre «notif
» para almacenar las notificaciones que serán visibles en el navegador. Esta consulta lo tienes que ejecutar en el PHPMyAdmin.
CREATE TABLE `notif` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `notif_msg` text NOT NULL, `notif_time` datetime DEFAULT NULL, `notif_repeat` int(11) DEFAULT '1', `notif_loop` int(11) NOT NULL DEFAULT '1', `publish_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `notif` (`id`, `title`, `notif_msg`, `notif_time`, `notif_repeat`, `notif_loop`, `publish_date`, `username`) VALUES (3, 'Meteoritos caéra en la Tierra', 'Llegada de los meteoritos a la tierra.', '2019-05-07 15:15:17', 1, 1, '2019-05-07 20:21:11', 'baulphp'); ALTER TABLE `notif` ADD PRIMARY KEY (`id`); ALTER TABLE `notif` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Ahora, también crearemos una tabla llamada «notif_user
«, en esta tabla se almacenara los usuarios que hacen login en nuestra página y/o sistema web. A continuación la consulta SQL que podrías ejecutar en el gestor de base de datos PHPMyAdmin.
CREATE TABLE `notif_user` ( `id` int(11) NOT NULL, `username` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `notif_user` (`id`, `username`, `password`) VALUES (1, 'baulphp', '12345'); ALTER TABLE `notif_user` ADD PRIMARY KEY (`id`); ALTER TABLE `notif_user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
Segundo paso: Crear formulario para login de usuarios.
En este punto tenemos que estructurar un formulario HTML para iniciar sesión en el navegador. Recordemos que las notificaciones serán visibles a los usuarios registrados y que hayan iniciado sesión en la página web.
<?php include('container.php');?> <div class="container"> <h2>Iniciar Sesión:</h2> <div class="row"> <div class="col-sm-4"> <form method="post"> <div class="form-group"> <?php if ($loginError ) { ?> <div class="alert alert-warning"><?php echo $loginError; ?></div> <?php } ?> </div> <div class="form-group"> <label for="username">Usuario:</label> <input type="username" class="form-control" name="username" required> </div> <div class="form-group"> <label for="pwd">Contraseña:</label> <input type="password" class="form-control" name="pwd" required> </div> <button type="submit" name="login" class="btn btn-default">Iniciar Sesion</button> </form><br> <strong>Datos demo:</strong><br> <strong>Usuario:</strong> baulphp <br> <strong>Contraseña:</strong> 12345 </div> </div> </div> <?php include('footer.php');?>
Un formulario no podría iniciar sesión. Por lo tanto, se tendría que apoyar en un lenguaje de programación como PHP y aquí mostraremos la estructura del mismo.
<?php session_start(); include('header.php'); $loginError = ''; if (!empty($_POST['username']) && !empty($_POST['pwd'])) { include ('Push.php'); $push = new Push(); $user = $push->loginUsers($_POST['username'], $_POST['pwd']); if(!empty($user)) { $_SESSION['username'] = $user[0]['username']; header("Location:index.php"); } else { $loginError = "Invalido el usuario o contraseña!"; } } ?>
Tercer paso: Ingresar notificación al sistema
Para que las notificaciones se emitan, primeramente tenemos que agregar una notificación para enviar a los usuarios. Por lo tanto, el fichero encargado de este trabajo es «manage_notification.php
«. Este fichero mostrara un formulario HTML en el cual nos permitirá crear la notificación con diversos campos.
<div class="container"> <h2>Ejemplo: Sistema de Notificación PUSH usando PHP y MySQL</h2> <a href="index.php">Portada</a> | <a href="logout.php">Salir</a> <hr> <div class="row"> <div class="col-sm-6"> <h3>Agregar nueva notificacion:</h3> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <table class="table borderless"> <tr> <td>Titulo</td> <td><input type="text" name="title" class="form-control" required></td> </tr> <tr> <td>Mensaje</td> <td><textarea name="msg" cols="50" rows="4" class="form-control" required></textarea></td> </tr> <tr> <td>Tiempo de Emision</td> <td><select name="time" class="form-control"><option>Ahora</option></select> </td> </tr> <tr> <td>Bucle (tiempo)</td> <td><select name="loops" class="form-control"> <?php for ($i=1; $i<=5 ; $i++) { ?> <option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?> </select></td> </tr> <tr> <td>Bucle cada (Minutos)</td> <td><select name="loop_every" class="form-control"> <?php for ($i=1; $i<=60 ; $i++) { ?> <option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?> </select> </td> </tr> <tr> <td>Por</td> <td><select name="user" class="form-control"> <?php $user = $push->listUsers(); foreach ($user as $key) { ?> <option value="<?php echo $key['username'] ?>"><?php echo $key['username'] ?></option> <?php } ?> </select></td> </tr> <tr> <td colspan=1></td> <td colspan=1></td> </tr> <tr> <td colspan=1></td> <td><button name="submit" type="submit" class="btn btn-info">Agregar Mensaje</button></td> </tr> </table> </form> </div> </div>

A continuación, para complementar el formulario mostraremos el script encargado de enviar esa información a la base de datos MySQL.
<?php if (isset($_POST['submit'])) { if(isset($_POST['msg']) and isset($_POST['time']) and isset($_POST['loops']) and isset($_POST['loop_every']) and isset($_POST['user'])) { $title = $_POST['title']; $msg = $_POST['msg']; $time = date('Y-m-d H:i:s'); $loop= $_POST['loops']; $loop_every=$_POST['loop_every']; $user = $_POST['user']; $isSaved = $push->saveNotification($title, $msg,$time,$loop,$loop_every,$user); if($isSaved) { echo '* Guardar nueva notificación de éxito'; } else { echo 'error guardando informacion'; } } else { echo '* completado el parámetro de arriba'; } } ?> <h3>Notificaciones Lista:</h3>
Una vez ingresada las notificaciones a la base de datos tendremos que mostrar esas notificaciones en registros para poder visualizarlo. En tal sentido, aquí les dejare el script que muestra las notificaciones ingresadas a la base de datos.
<h3>Notificaciones Lista:</h3> <table class="table"> <thead> <tr> <th>No</th> <th>Siguiente horario</th> <th>Titulo</th> <th>Mensaje</th> <th>permanece</th> <th>Usuario</th> </tr> </thead> <tbody> <?php $a =1; $notifList = $push->listNotification(); foreach ($notifList as $key) { ?> <tr> <td><?php echo $a ?></td> <td><?php echo $key['notif_time'] ?></td> <td><?php echo $key['title'] ?></td> <td><?php echo $key['notif_msg'] ?></td> <td><?php echo $key['notif_loop']; ?></td> <td><?php echo $key['username'] ?></td> </tr> <?php $a++; } ?> </tbody> </table> </div>
Cuarto paso: Crear la conexión con la base de datos
La conexión de PHP y MySQL es muy importante para este sistema. Por lo tanto, el fichero que maneja la conexión se llama «Push.php
«. Aquí les dejare el contenido de dicho fichero.
<?php class Push{ private $host = 'localhost'; private $user = 'root'; private $password = ''; private $database = 'php_push'; private $notifTable = 'notif'; private $userTable = 'notif_user'; private $dbConnect = false; public function __construct(){ if(!$this->dbConnect){ $conn = new mysqli($this->host, $this->user, $this->password, $this->database); if($conn->connect_error){ die("Error failed to connect to MySQL: " . $conn->connect_error); }else{ $this->dbConnect = $conn; } } } private function getData($sqlQuery) { $result = mysqli_query($this->dbConnect, $sqlQuery); if(!$result){ die('Error in query: '. mysqli_error()); } $data= array(); while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $data[]=$row; } return $data; } public function listNotification(){ $sqlQuery = 'SELECT * FROM '.$this->notifTable; return $this->getData($sqlQuery); } public function listNotificationUser($user){ $sqlQuery = "SELECT * FROM ".$this->notifTable." WHERE username='$user' AND notif_loop > 0 AND notif_time <= CURRENT_TIMESTAMP()"; return $this->getData($sqlQuery); } public function listUsers(){ $sqlQuery = "SELECT * FROM ".$this->userTable." WHERE username != 'admin'"; return $this->getData($sqlQuery); } public function loginUsers($username, $password){ $sqlQuery = "SELECT id as userid, username, password FROM ".$this->userTable." WHERE username='$username' AND password='$password'"; return $this->getData($sqlQuery); } public function saveNotification($msg, $time, $loop, $loop_every, $user){ $sqlQuery = "INSERT INTO ".$this->notifTable."(notif_msg, notif_time, notif_repeat, notif_loop, username) VALUES('$msg', '$time', '$loop', '$loop_every', '$user')"; $result = mysqli_query($this->dbConnect, $sqlQuery); if(!$result){ return ('Error in query: '. mysqli_error()); } else { return $result; } } public function updateNotification($id, $nextTime) { $sqlUpdate = "UPDATE ".$this->notifTable." SET notif_time = '$nextTime', publish_date=CURRENT_TIMESTAMP(), notif_loop = notif_loop-1 WHERE id='$id')"; mysqli_query($this->dbConnect, $sqlUpdate); } } ?>

CONCLUSION DEL SISTEMA
En este artículo describimos las características, los ficheros necesarios y como funciona este sistema de notificaciones con ventanas emergentes.
Su uso es recomendado y su implementación es muy sencilla, solo tenemos que adaptarlo a nuestras necesidades. Sin embargo, tenemos que usarlo con moderación.
Además, les dejare un archivo comprimido donde contendrá los ficheros necesarios y la base de datos del sistema para que puedan instalarlo sin problemas y realizar las respectivas pruebas.